<template>
  <el-card>
    <h2>修改活动</h2>
    <el-form :model="activity" label-width="100px">
      <el-form-item label="标题">
        <el-input v-model="activity.title" />
      </el-form-item>
      <el-form-item label="地点">
        <el-input v-model="activity.location" />
      </el-form-item>
      <el-form-item label="开始时间">
        <el-date-picker v-model="activity.startTime" type="datetime" style="width:100%" />
      </el-form-item>
      <el-form-item label="结束时间">
        <el-date-picker v-model="activity.endTime" type="datetime" style="width:100%" />
      </el-form-item>
      <el-form-item label="内容">
        <el-input v-model="activity.content" type="textarea" />
      </el-form-item>
      <el-form-item label="分数">
        <el-input-number v-model="activity.point" :min="0" />
      </el-form-item>
      <!-- 状态只读显示 -->
      <el-form-item label="当前状态">
        <el-tag>{{ statusLabel(activity.status) }}</el-tag>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateActivity">保存修改</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const activity = ref({
  actId: null,
  title: '',
  content: '',
  startTime: '',
  endTime: '',
  location: '',
  status: '', // 只读显示
  orgId: Number(localStorage.getItem('loginId')),
  point: 0
})

const statusLabel = (status) => {
  switch (status) {
    case 'DRAFT': return '草稿'
    case 'PENDING': return '待审核'
    case 'APPROVED_C': return '通过C'
    case 'APPROVED_B': return '通过B'
    case 'APPROVED': return '通过'
    case 'REJECTED': return '驳回'
    case 'COMPLETED': return '已完成'
    default: return status
  }
}

onMounted(async () => {
  const actId = route.params.actId;
  try {
    const res = await axios.get(`http://localhost:8080/orgs/getActivity/${actId}`);
    if (res.data && res.data.code === 200) {
      Object.assign(activity.value, res.data.data);
    } else {
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '获取活动详情失败');
    }
  } catch (e) {
    ElMessage.error('获取活动详情失败');
  }
});

const updateActivity = async () => {
  try {
    // 不提交status字段
    const { status, ...submitData } = activity.value;
    const res = await axios.put(
      `http://localhost:8080/orgs/${activity.value.actId}/${activity.value.orgId}/activities`,
      { ...submitData }
    );
    if (res.data && res.data.code === 200) {
      // 用后端返回的活动对象刷新本地状态
      Object.assign(activity.value, res.data.activity);
      ElMessage.success('活动修改成功');
      router.back();
    } else {
      ElMessage.error(res.data && res.data.msg ? res.data.msg : '保存失败');
    }
  } catch (e) {
    ElMessage.error('保存失败');
  }
};
</script>